package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.commons.exception.CommentException;
import com.woniuxy.commons.exception.code.CommentExceptionCode;
import com.woniuxy.commons.utils.BeanCopyUtil;
import com.woniuxy.commons.utils.CommonsUtil;
import com.woniuxy.commons.utils.DateUtil;
import com.woniuxy.controller.form.CommentCreatForm;
import com.woniuxy.controller.form.CommentStaticForm;
import com.woniuxy.controller.form.CommentStoreShowForm;
import com.woniuxy.controller.form.StoreReplyForm;
import com.woniuxy.dao.model.CommentInfo;
import com.woniuxy.dao.CommentInfoDao;
import com.woniuxy.dao.model.DietOrder;
import com.woniuxy.service.CommentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.DietOrderService;
import com.woniuxy.service.dto.*;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author psy
 * @since 2022-06-28
 */
@Service
public class CommentInfoServiceImpl extends ServiceImpl<CommentInfoDao, CommentInfo> implements CommentInfoService {
    @Resource
    private CommentInfoDao commentInfoDao;
    @Resource
    private DietOrderService dietOrderService;
    @Resource
    private CommentInfoService commentInfoService;
    @Override
    public boolean addComment(CommentCreatForm commentCreatForm) {
        CommentInfo commentInfo = BeanCopyUtil.copyOne(commentCreatForm, CommentInfo.class);
        boolean update = dietOrderService.update(new UpdateWrapper<DietOrder>().eq("orderNum", commentCreatForm.getOrderNum()).set("evaluate", 1));
        boolean save = commentInfoService.save(commentInfo);
        if(save){
            return true;
        }else{
            throw new CommentException(CommentExceptionCode.COMMENT_ADD_FAIL.getCode(),CommentExceptionCode.COMMENT_ADD_FAIL.getMessage());
        }
    }

    @Override
    public Long getId(String orderNum) {
        CommentInfo orderNum1 = commentInfoService.getOne(new QueryWrapper<CommentInfo>().eq("orderNum", orderNum));
        Long id = orderNum1.getId();
        return id;
    }

    @Override
    public boolean replay(StoreReplyForm storeReplyForm) {
        boolean update = commentInfoService.update(new UpdateWrapper<CommentInfo>().eq("id", storeReplyForm.getId()).set("replay", storeReplyForm.getReplay()).set("replayFlag", storeReplyForm.getReplayFlag()));
        if(update){
            return true;
        }else{
            throw new CommentException(CommentExceptionCode.COMMENT_REPLAY_FAIL.getCode(),CommentExceptionCode.COMMENT_REPLAY_FAIL.getMessage());
        }
    }

    @Override
    public boolean delComment(Long id) {
        boolean b = commentInfoService.removeById(id);
        if(b){
            return true;
        }else{
            throw new CommentException(CommentExceptionCode.COMMENT_DEL_FAIL.getCode(),CommentExceptionCode.COMMENT_DEL_FAIL.getMessage());
        }
    }

    @Override
    public Page<CommentStoreDto> getCommentByStoreId(Long id,Integer pageNum,Integer pageSize) {
        Page<CommentInfo> page = new Page<>(pageNum,pageSize);
        Page<CommentInfo> storeId = commentInfoService.page(page, new QueryWrapper<CommentInfo>().eq("storeId", id));
        Page<CommentStoreDto> commentStoreDtoPage = BeanCopyUtil.copyPageInfo(storeId, CommentStoreDto.class);
        return commentStoreDtoPage;

    }

    @Override
    public StoreShowCommentDto getCommentsInStore(CommentStoreShowForm commentStoreShowForm) {
        List<CommentInfo> storeId = commentInfoService.list(new QueryWrapper<CommentInfo>().eq("storeId", commentStoreShowForm.getStoreId()));
        StoreShowCommentDto storeShowCommentDto=new StoreShowCommentDto();
        if(null==storeId){
            storeShowCommentDto.setAllComment(0);
            storeShowCommentDto.setGoodComment(0);
            storeShowCommentDto.setPoorComment(0);
            storeShowCommentDto.setPictureComment(0);
        }else{
            storeShowCommentDto.setAllComment(storeId.size());
            int good=0;
            int poor=0;
            int picture=0;
            for (CommentInfo commentInfo : storeId) {
                if(commentInfo.getStoreScore()==5){
                    good++;
                }else if(commentInfo.getStoreScore()==1){
                    poor++;
                }
                if(commentInfo.getPictureFlag()==1){
                    picture++;
                }
            }
            storeShowCommentDto.setGoodComment(good);
            storeShowCommentDto.setPoorComment(poor);
            storeShowCommentDto.setPictureComment(picture);
        }
        if(commentStoreShowForm.getStoreScore()==5){
            Page<CommentsStoreShowDto> page = new Page<>(commentStoreShowForm.getPageNum(), commentStoreShowForm.getPageSize());
            Page<CommentsStoreShowDto> commentsInStore = commentInfoDao.getCommentsInStore(page, commentStoreShowForm.getStoreId(), commentStoreShowForm.getStoreScore());
            storeShowCommentDto.setCommentsStoreShowDtoPage(commentsInStore);
            return storeShowCommentDto;
        }else if(commentStoreShowForm.getStoreScore()==1){
            Page<CommentsStoreShowDto> page = new Page<>(commentStoreShowForm.getPageNum(), commentStoreShowForm.getPageSize());
            Page<CommentsStoreShowDto> commentsInStore = commentInfoDao.getCommentsInStore(page, commentStoreShowForm.getStoreId(), commentStoreShowForm.getStoreScore());
            storeShowCommentDto.setCommentsStoreShowDtoPage(commentsInStore);
            return storeShowCommentDto;
        }else if(commentStoreShowForm.getPictureFlag()==1){
            Page<CommentsStoreShowDto> page = new Page<>(commentStoreShowForm.getPageNum(), commentStoreShowForm.getPageSize());
            Page<CommentsStoreShowDto> commentsInStoreByPictrue = commentInfoDao.getCommentsInStoreByPictrue(page,commentStoreShowForm.getStoreId(),commentStoreShowForm.getPictureFlag());
            storeShowCommentDto.setCommentsStoreShowDtoPage(commentsInStoreByPictrue);
            return storeShowCommentDto;
        }else if(commentStoreShowForm.getStoreScore()==2){
            Page<CommentsStoreShowDto> page = new Page<>(commentStoreShowForm.getPageNum(), commentStoreShowForm.getPageSize());
            Page<CommentsStoreShowDto> commentOther = commentInfoDao.getCommentOther(page, commentStoreShowForm.getStoreId());
            storeShowCommentDto.setCommentsStoreShowDtoPage(commentOther);
            return storeShowCommentDto;
        }else{
            Page<CommentsStoreShowDto> page = new Page<>(commentStoreShowForm.getPageNum(), commentStoreShowForm.getPageSize());
            Page<CommentsStoreShowDto> comment = commentInfoDao.getComment(page, commentStoreShowForm.getStoreId());
            storeShowCommentDto.setCommentsStoreShowDtoPage(comment);
            return storeShowCommentDto;
        }
    }

    @Override
    public CommentByOrderNumDto getCommentByOrderNum(String orderNum) {
        CommentInfo orderNum1 = commentInfoService.getOne(new QueryWrapper<CommentInfo>().eq("orderNum", orderNum));
        if(orderNum1.getPictureFlag()==1){
            CommentByOrderNumDto commentByOrderNum = commentInfoDao.getCommentByOrderNum(orderNum);
            return commentByOrderNum;
        }else{
            CommentByOrderNumDto commentByOrderNumDto = BeanCopyUtil.copyOne(orderNum1, CommentByOrderNumDto.class);
            return commentByOrderNumDto;
        }

    }

    @Override
    public ScoreStoreDto getStoreScore(Long storeId) {
        ArrayList<ScoreStoreDto> storeScore = commentInfoDao.getStoreScore(storeId);
        int size = storeScore.size();
        double storeScoree=0;
        double dishesScore=0;
        double dphScore=0;
        for (ScoreStoreDto scoreStoreDto : storeScore) {
            storeScoree+=scoreStoreDto.getStoreScore();
            dishesScore+=scoreStoreDto.getDishesScore();
            dphScore+=scoreStoreDto.getDphScore();
        }
        ScoreStoreDto scoreStoreDto=new ScoreStoreDto();
        DecimalFormat format=new DecimalFormat("0.00");
        double format1 = Double.parseDouble(format.format(storeScoree / size));
        double format2 = Double.parseDouble(format.format(dishesScore / size));
        double format3 = Double.parseDouble(format.format(dphScore / size));
        scoreStoreDto.setStoreScore(format1);
        scoreStoreDto.setDishesScore(format2);
        scoreStoreDto.setDphScore(format3);
        double v = Double.parseDouble(format.format((storeScoree / size + dishesScore / size + dphScore / size)/3));
        scoreStoreDto.setStoreScores(v);
        return scoreStoreDto;
    }

    @Override
    public Page<CommentStoreDto> getCommentStoreNotReplay(Long id, Integer pageNum, Integer pageSize) {
        Page<CommentInfo> page = new Page<>(pageNum,pageSize);
        Page<CommentInfo> storeId = commentInfoService.page(page, new QueryWrapper<CommentInfo>().eq("storeId", id).eq("replayFlag",0));
        Page<CommentStoreDto> commentStoreDtoPage = BeanCopyUtil.copyPageInfo(storeId, CommentStoreDto.class);
        return commentStoreDtoPage;
    }

    @Override
    public CommentStaticDto commentStatic(CommentStaticForm commentStaticForm) {
        System.out.println("++++++++++++++");
        System.out.println(commentStaticForm);
        //如果开始时间和结束时间为空，那么不触发后面的逻辑，没有根据满意度查询这一说
        CommentStaticDto commentStaticDto=new CommentStaticDto();
        if("Invalid date".equals(commentStaticForm.getStartTime())||"Invalid date".equals(commentStaticForm.getEndTime())){
            commentStaticDto.setGoodComment(0);
            commentStaticDto.setGoodCommentPercent("0%");
            commentStaticDto.setMidComment(0);
            commentStaticDto.setPoorComment(0);
            commentStaticDto.setTotalComment(0);
           return commentStaticDto;
        }
        String startTime = commentStaticForm.getStartTime();
        String endTime = commentStaticForm.getEndTime();
//        Long start = DateUtil.parseDateString(commentStaticForm.getStartTime(), "yyyy-MM-dd HH:mm:ss");
//        Long end = DateUtil.parseDateString(commentStaticForm.getEndTime(), "yyyy-MM-dd HH:mm:ss");
        //只有时间段查询
        UserDetailsDto userDetailsDto = (UserDetailsDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long id = userDetailsDto.getId();

//        Page<CommentStoreDto> commentStoreDtos = commentStaticDto.getCommentStoreDtos();
        Page<CommentInfo> commentInfoPage = new Page<>(commentStaticForm.getPageNum(), commentStaticForm.getPageSize());
        Page<CommentInfo> storeId = commentInfoService.page(commentInfoPage, new QueryWrapper<CommentInfo>().eq("storeId", id));
        int good=0;
        int poor=0;
        int mid=0;
        DecimalFormat format=new DecimalFormat("0.00%");
        if(null==storeId.getRecords()){
            commentStaticDto.setGoodComment(0);
            commentStaticDto.setGoodCommentPercent("0%");
            commentStaticDto.setMidComment(0);
            commentStaticDto.setPoorComment(0);
            commentStaticDto.setTotalComment(0);
            commentStaticDto.setCommentStoreDtos(null);
            return commentStaticDto;
        }else{
            //纯时间段查询
            Page<CommentInfo> page1 = commentInfoService.page(commentInfoPage, new QueryWrapper<CommentInfo>().apply("UNIX_TIMESTAMP(date)>=UNIX_TIMESTAMP('" + startTime + "')")
                    .apply("UNIX_TIMESTAMP(date)<=UNIX_TIMESTAMP('" + endTime + "')"));
            if(null==page1.getRecords()){
                commentStaticDto.setGoodComment(0);
                commentStaticDto.setGoodCommentPercent("0%");
                commentStaticDto.setMidComment(0);
                commentStaticDto.setPoorComment(0);
                commentStaticDto.setTotalComment(0);
                commentStaticDto.setCommentStoreDtos(null);
                return commentStaticDto;
            }
            //需要返回的评价信息列表集合(分页)
            Page<CommentStoreDto> commentStoreDtoPage = BeanCopyUtil.copyPageInfo(page1, CommentStoreDto.class);
            commentStaticDto.setCommentStoreDtos(commentStoreDtoPage);
            List<CommentInfo> records = commentInfoService.list(new QueryWrapper<CommentInfo>().apply("UNIX_TIMESTAMP(date)>=UNIX_TIMESTAMP('" + startTime + "')")
                    .apply("UNIX_TIMESTAMP(date)<=UNIX_TIMESTAMP('" + endTime + "')"));
            commentStaticDto.setTotalComment(records.size());
            for (CommentInfo record : records) {
                if(record.getStoreScore()==5){
                    good++;
                }else if(record.getStoreScore()==1){
                    poor++;
                }else{
                    mid++;
                }
            }
            commentStaticDto.setGoodComment(good);
            commentStaticDto.setPoorComment(poor);
            commentStaticDto.setMidComment(mid);
            double percent=good/(records.size()*1.0);
            String format1 = format.format(percent);
            commentStaticDto.setGoodCommentPercent(format1);
            //在时间段内的评价内容模糊查询(不更新评分，仅做查询评价用)
            String text = commentStaticForm.getText();
            Integer storeScore = commentStaticForm.getStoreScore();
            if(!"null".equals(text)&&!"".equals(text)&&null!=text){
                Page<CommentInfo> page = commentInfoService.page(commentInfoPage, new QueryWrapper<CommentInfo>().like("content", text).or().like("userName", text)
                        .apply("UNIX_TIMESTAMP(date)>=UNIX_TIMESTAMP('" + startTime + "')")
                        .apply("UNIX_TIMESTAMP(date)<=UNIX_TIMESTAMP('" + endTime + "')"));
                if(null==page.getRecords()){
                    return null;
                }
                if(storeScore!=0){
                    //storeScore==5,好评，storeScore==1，差评
                    Page<CommentInfo> pageScore = commentInfoService.page(commentInfoPage, new QueryWrapper<CommentInfo>().eq("storeScore", storeScore)
                            .apply("UNIX_TIMESTAMP(date)>=UNIX_TIMESTAMP('" + startTime + "')")
                            .apply("UNIX_TIMESTAMP(date)<=UNIX_TIMESTAMP('" + endTime + "')")
                            .like("content", text).or().like("userName", text));
                    if(null==pageScore.getRecords()){
                        return null;
                    }
                    Page<CommentStoreDto> commentStaticDtoPage = BeanCopyUtil.copyPageInfo(pageScore, CommentStoreDto.class);
                    commentStaticDto.setCommentStoreDtos(commentStaticDtoPage);
                    if(storeScore==2){
                        Page<CommentInfo> pageMid = commentInfoService.page(commentInfoPage, new QueryWrapper<CommentInfo>().in("storeScore",2,3,4)
                                .apply("UNIX_TIMESTAMP(date)>=UNIX_TIMESTAMP('" + startTime + "')")
                                .apply("UNIX_TIMESTAMP(date)<=UNIX_TIMESTAMP('" + endTime + "')")
                                .like("content", text).or().like("userName", text));
                        if(null==pageMid.getRecords()){
                            return null;
                        }
                        Page<CommentStoreDto> commentStaticDtoPageMid = BeanCopyUtil.copyPageInfo(page, CommentStoreDto.class);
                        commentStaticDto.setCommentStoreDtos(commentStaticDtoPageMid);
                        return commentStaticDto;
                    }
                    return commentStaticDto;
                }
                Page<CommentStoreDto> commentStaticDtoPage = BeanCopyUtil.copyPageInfo(page, CommentStoreDto.class);
                commentStaticDto.setCommentStoreDtos(commentStaticDtoPage);
                return commentStaticDto;
            }
            //在时间段内的满意度查询（点击模糊查询或者满意度查询都会把另一个覆盖掉,前端传参需要注意）(不更新评分，仅做查询评价用)

            if(storeScore!=0){
                //storeScore==5,好评，storeScore==1，差评
                    Page<CommentInfo> page = commentInfoService.page(commentInfoPage, new QueryWrapper<CommentInfo>().eq("storeScore", storeScore)
                            .apply("UNIX_TIMESTAMP(date)>=UNIX_TIMESTAMP('" + startTime + "')")
                            .apply("UNIX_TIMESTAMP(date)<=UNIX_TIMESTAMP('" + endTime + "')"));
                    if(null==page.getRecords()){
                        return null;
                    }
                    Page<CommentStoreDto> commentStaticDtoPage = BeanCopyUtil.copyPageInfo(page, CommentStoreDto.class);
                    commentStaticDto.setCommentStoreDtos(commentStaticDtoPage);
                    if(storeScore==2){
                        Page<CommentInfo> pageMid = commentInfoService.page(commentInfoPage, new QueryWrapper<CommentInfo>().in("storeScore",2,3,4)
                                .apply("UNIX_TIMESTAMP(date)>=UNIX_TIMESTAMP('" + startTime + "')")
                                .apply("UNIX_TIMESTAMP(date)<=UNIX_TIMESTAMP('" + endTime + "')"));
                        if(null==pageMid.getRecords()){
                            return null;
                        }
                        Page<CommentStoreDto> commentStaticDtoPageMid = BeanCopyUtil.copyPageInfo(page, CommentStoreDto.class);
                        commentStaticDto.setCommentStoreDtos(commentStaticDtoPageMid);
                        return commentStaticDto;
                    }
                    return commentStaticDto;
            }
            return commentStaticDto;
        }
    }

}
